package com.feizhoutuobang.shapeline.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

public abstract class Shell {
	
	private static final Logger LOG = Logger.getLogger(Shell.class);

	public static int execute(String[] command) {
		//! 为什么要加这个数组呢，好像主要是为了在不同os之间兼容吧。
		String[] cmd = new String[4];
		String osName = System.getProperty("os.name");
		LOG.debug("osName:"+osName);
		
		if( osName.equals( "Windows NT") ||osName.equals( "Windows XP") || osName.equals("Windows 7")) {
			cmd[0] = "cmd.exe";
			cmd[1] = "/C";
			cmd[2] = command[0];
			cmd[3] = command[1];
		} 
		else if( osName.equals( "Windows 95") ) {
			cmd[0] = "command.com";
			cmd[1] = "/C";
			cmd[2] = command[0];
			cmd[3] = command[1];
		}
		else if (osName.toLowerCase().contains("windows")) {
			cmd[0] = "cmd.exe";
			cmd[1] = "/C";
			cmd[2] = command[0];
			cmd[3] = command[1];
		}
		else if (osName.toLowerCase().contains("linux")) {
			cmd = new String[2];
			cmd[0] = command[0];
			cmd[1] = command[1];
		}
		LOG.debug(cmd);
		
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			Process p = Runtime.getRuntime().exec(cmd);
			
			//! 注意，这里必须把Error信息取出来打印，否则Process会hang住，永远不结束
			//InputStream stderr = p.getErrorStream();
			//InputStreamReader isr = new InputStreamReader(stderr);
			//BufferedReader br = new BufferedReader(isr);
			//String line = null;

//	           System.out.println("<ERROR>");

//	           while((line = br.readLine()) != null)
//
//	              System.out.println(line);

//	           System.out.println("</ERROR>");

	           

			//! 输出标准输出 这里也可以不输出
			is = p.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			LOG.debug("<OUTPUT>");
			String line = null;
			while((line = br.readLine()) != null) {
				LOG.debug(line);
			}
			LOG.debug("</OUTPUT>");
			
			int exitVal = p.waitFor();
			LOG.debug("ProcessexitValue: "+ exitVal);
			return exitVal;
		}
		catch(Exception e) {
			LOG.debug("", e);
			return -1;
		}
		finally {
			try {br.close();} catch (Exception e) {}
			try {isr.close();} catch (Exception e) {}
			try {is.close();} catch (Exception e) {}
		}
	}
}
